<?php

namespace App\Http\Middleware;

use App\Libraries\Enigma\EnigmaHelper;
use Closure;
use Illuminate\Http\Request;

class ApiEncrypt
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 执行下一个中间件
        $response = $next($request);

        $responseData = $response->original;
        if (isset($responseData['data'])) {
             $responseData['data'] = EnigmaHelper::encrypt($responseData['data']);
        }

        // 更新响应的内容
        $response->setContent(json_encode($responseData));

        return $response;
    }
}
